#!/bin/bash
# 后台启动脚本（使用nohup）

cd "$(dirname "$0")"

# 激活虚拟环境
if [ -d "venv" ]; then
    source venv/bin/activate
else
    echo "❌ 虚拟环境不存在，请先运行 ./deploy.sh"
    exit 1
fi

# 检查是否已经在运行
if [ -f "server.pid" ]; then
    PID=$(cat server.pid)
    if ps -p $PID > /dev/null 2>&1; then
        echo "⚠️  服务器已在运行 (PID: $PID)"
        echo "如需重启，请先运行 ./stop.sh"
        exit 1
    fi
fi

echo "=========================================="
echo "启动定位后台服务器（后台模式）"
echo "=========================================="

# 后台启动
nohup python3 server.py > server.log 2>&1 &
SERVER_PID=$!

# 保存PID
echo $SERVER_PID > server.pid

sleep 2

# 检查是否启动成功
if ps -p $SERVER_PID > /dev/null 2>&1; then
    echo "✅ 服务器启动成功！"
    echo "PID: $SERVER_PID"
    echo ""
    echo "管理界面: http://$(hostname -I | awk '{print $1}'):5000"
    echo "日志文件: $(pwd)/server.log"
    echo ""
    echo "常用命令:"
    echo "  查看日志: tail -f server.log"
    echo "  停止服务: ./stop.sh"
    echo "=========================================="
else
    echo "❌ 服务器启动失败"
    echo "查看日志: cat server.log"
    rm -f server.pid
    exit 1
fi


